/**
	 * DefaultBuddyListWindow.java
	 *
	 * Created on Mar 12, 2009, 10:39:45 PM
	 * @author Lance
	 */
package client.ui.theme.defaultTheme;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;

import server.BuddyList;
import server.Group;
import server.Person;
import server.Preferences;
import server.Status;
import client.engine.ChatEngine;
import client.ui.IBuddyListWindow;

public class DefaultBuddyListWindow extends javax.swing.JFrame
implements IBuddyListWindow {
	
	private javax.swing.JMenu PreferencesMenuItem;
    private javax.swing.JMenuItem PreferencesMenuOption;
    private javax.swing.JButton addBuddyButton;
    private javax.swing.JMenuItem addGroupMenuOption;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JList offlineBuddyJList;
    private javax.swing.JScrollPane offlineBuddyScrollPane;
    private javax.swing.JList onlineBuddyJList;
    private javax.swing.JScrollPane onlineBuddyScrollPane;
    private javax.swing.JButton removeBuddyButton;
    private javax.swing.JMenuItem removeGroupMenuOption;
    private javax.swing.JMenuItem viewHistoryOption;
    private ChatEngine engine;

	    /** Creates new form NewJFrame */
	    public DefaultBuddyListWindow() {
	        initComponents();
	        this.setLocationRelativeTo(null);
	    }

	    
	    private void initComponents() {

	    	jLabel1 = new javax.swing.JLabel();
	        jLabel2 = new javax.swing.JLabel();
	        jLabel3 = new javax.swing.JLabel();
	        addBuddyButton = new javax.swing.JButton();
	        removeBuddyButton = new javax.swing.JButton();
	        onlineBuddyScrollPane = new javax.swing.JScrollPane();
	        onlineBuddyJList = new javax.swing.JList();
	        offlineBuddyScrollPane = new javax.swing.JScrollPane();
	        offlineBuddyJList = new javax.swing.JList();
	        jMenuBar1 = new javax.swing.JMenuBar();
	        PreferencesMenuItem = new javax.swing.JMenu();
	        PreferencesMenuOption = new javax.swing.JMenuItem();
	        addGroupMenuOption = new javax.swing.JMenuItem();
	        removeGroupMenuOption = new javax.swing.JMenuItem();
	        viewHistoryOption = new javax.swing.JMenuItem();

	        this.setTitle("Parlanchin - Buddy List");
	        
	        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
	        addWindowListener(new java.awt.event.WindowAdapter() {
	            public void windowClosing(java.awt.event.WindowEvent evt) {
	                formWindowClosing(evt);
	            }
	        });

	        jLabel1.setText("Parlanchin Buddy List");

	        jLabel2.setText("Online Buddies");

	        jLabel3.setText("Offline Buddies");

	        addBuddyButton.setText("Add Buddy");
	        addBuddyButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                addBuddyButtonActionPerformed(evt);
	            }
	        });

	        removeBuddyButton.setText("Remove Buddy");
	        removeBuddyButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	                removeBuddyButtonActionPerformed(evt);
	            }
	        });

	        onlineBuddyJList.addMouseListener(new java.awt.event.MouseAdapter() {
	            public void mouseClicked(java.awt.event.MouseEvent evt) {
	                onlineBuddyJListMouseClicked(evt);
	            }
	        });
	        onlineBuddyScrollPane.setViewportView(onlineBuddyJList);

	        offlineBuddyJList.addMouseListener(new java.awt.event.MouseAdapter() {
	            public void mouseClicked(java.awt.event.MouseEvent evt) {
	                offlineBuddyJListMouseClicked(evt);
	            }
	        });
	        offlineBuddyScrollPane.setViewportView(offlineBuddyJList);

	        PreferencesMenuItem.setText("File");

	        PreferencesMenuOption.setText("Preferences");
	        PreferencesMenuOption.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	PreferencesMenuOptionActionPerformed(evt);
	            }
	        });
	        PreferencesMenuItem.add(PreferencesMenuOption);

	        addGroupMenuOption.setText("Add Group");
	        addGroupMenuOption.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	addGroupMenuOptionActionPerformed(evt);
	            }
	        });
	        PreferencesMenuItem.add(addGroupMenuOption);

	        removeGroupMenuOption.setText("Remove Group");
	        removeGroupMenuOption.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	removeGroupMenuOptionActionPerformed(evt);
	            }
	        });
	        PreferencesMenuItem.add(removeGroupMenuOption);
	        
	        viewHistoryOption.setText("View Conversation History");
	        viewHistoryOption.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
	            	viewHistoryOptionActionPerformed(evt);
	            }
	        });
	        PreferencesMenuItem.add(viewHistoryOption);

	        jMenuBar1.add(PreferencesMenuItem);

	        setJMenuBar(jMenuBar1);

	        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
	        getContentPane().setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(jLabel2))
	                    .addGroup(layout.createSequentialGroup()
	                        .addGap(59, 59, 59)
	                        .addComponent(jLabel1))
	                    .addGroup(layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(jLabel3))
	                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(addBuddyButton, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
	                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                        .addComponent(removeBuddyButton))
	                    .addGroup(layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(onlineBuddyScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE))
	                    .addGroup(layout.createSequentialGroup()
	                        .addContainerGap()
	                        .addComponent(offlineBuddyScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)))
	                .addContainerGap())
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(jLabel1)
	                .addGap(7, 7, 7)
	                .addComponent(jLabel2)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(onlineBuddyScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(jLabel3)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addComponent(offlineBuddyScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(addBuddyButton)
	                    .addComponent(removeBuddyButton))
	                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	        );

	        pack();
	    }

	    
		@Override
		public void displayBuddyList(BuddyList myBuddies) {
			onlineBuddyJList.removeAll();
			offlineBuddyJList.removeAll();
			
			Preferences pref = engine.getPreferences();
			
			ArrayList<String> onlineBuddies = new ArrayList<String>();
			ArrayList<String> offlineBuddies = new ArrayList<String>();
			
			Iterator<Group> groupIterator = myBuddies.getGroups();
			
			while(groupIterator.hasNext())
			{
				Group g = groupIterator.next();
				Iterator<Person> buddyIterator = g.getMembers();
				
				if(pref.isGrouped()){
					onlineBuddies.add(g.getName());
					offlineBuddies.add(g.getName());
				}
				
				while(buddyIterator.hasNext())
				{
					Person p = buddyIterator.next();
					Status status = p.getStatus();
					
					if(status == Status.ONLINE)
					{
				        onlineBuddies.add("  " + p.getUsername());
					}
					else if(status == Status.OFFLINE)
					{
						if(pref.isShowOffline()){
							offlineBuddies.add("  " + p.getUsername());
						}
					}
				}
				
			}

			String[] names = new String[onlineBuddies.size()];
			onlineBuddies.toArray(names);
			final String[] onlinecontent = names;
			onlineBuddyJList.setModel(new javax.swing.AbstractListModel() {
	            String[] strings = onlinecontent;
	            public int getSize() { return strings.length; }
	            public Object getElementAt(int i) { return strings[i]; }
	        });
			
			names = new String[offlineBuddies.size()];
			offlineBuddies.toArray(names);
			final String[] offlinecontent = names;
			offlineBuddyJList.setModel(new javax.swing.AbstractListModel() {
	            String[] strings = offlinecontent;
	            public int getSize() { return strings.length; }
	            public Object getElementAt(int i) { return strings[i]; }
	        });
			
			onlineBuddyScrollPane.setViewportView(onlineBuddyJList);
			offlineBuddyScrollPane.setViewportView(offlineBuddyJList);
		}

		@Override
		public void setChatEngine(ChatEngine engine) {
			
			this.engine = engine;
			
		}
		
		private void removeBuddyButtonActionPerformed(java.awt.event.ActionEvent evt) {

			String buddyName = JOptionPane.showInputDialog("Insert buddy to be removed:");
			
			engine.removeBuddy(buddyName);
			
		}

		private void addBuddyButtonActionPerformed(java.awt.event.ActionEvent evt) {
	        
			String buddyName = JOptionPane.showInputDialog("Insert your new buddy's name:");
			String groupName = null;
			
			groupName = JOptionPane.showInputDialog("Insert group to add the new contact:");
				
			if(engine.getBuddyList().findGroup(groupName) == null){
				JOptionPane.showMessageDialog(this, "Group doesn't exist");
			}else{
				engine.addBuddy(buddyName, groupName);
			}
			
	    }
		
	    private void PreferencesMenuOptionActionPerformed(java.awt.event.ActionEvent evt) {
	        
	    	this.engine.showPreferencesWindow();
	    	
	    }

	    private void addGroupMenuOptionActionPerformed(java.awt.event.ActionEvent evt) {
	        
	    	String groupName = JOptionPane.showInputDialog("Insert a name for the group:");
	    	
	    	if(groupName != null && !groupName.equals("")){
	    		engine.createGroup(groupName);
	    	}
	    	
	    }

	    private void removeGroupMenuOptionActionPerformed(java.awt.event.ActionEvent evt) {
	        
	    	String groupName = JOptionPane.showInputDialog("Insert a name for the group (make sure the group has no buddies):");
	    	
	    	if(groupName != null && !groupName.equals("")){
	    		if(!engine.removeGroup(groupName)){
	    			JOptionPane.showMessageDialog(this, "Group couldn't be removed.");
	    		}else{
	    			JOptionPane.showMessageDialog(this, "Group successfully removed.");
	    		}
	    	}
	    	
	    }

		private void onlineBuddyJListMouseClicked(MouseEvent evt) {
			
			if(evt.getClickCount() >= 2){ // Double-click to open conversation
				String buddyName = (String) onlineBuddyJList.getSelectedValue();
				if(buddyName.startsWith("  ")){
					this.engine.openConversation(buddyName.substring(2));
				}
			}
			
		}
		
		private void offlineBuddyJListMouseClicked(MouseEvent evt) {
			
			if(evt.getClickCount() >= 2){
				String buddyName = (String) offlineBuddyJList.getSelectedValue();
				if(buddyName.startsWith("  ")){
					String receiver = buddyName.substring(2);
					ArrayList<String> participants = new ArrayList<String>();
					participants.add(receiver);
					participants.add(engine.getUsername());
					this.engine.conversationOpened(participants, "offline"+receiver);
				}
			}
			
		}
		
		private void formWindowClosing(WindowEvent evt) {
			
			int response = JOptionPane.showConfirmDialog(this, "Do you want to exit?", "Exit", JOptionPane.YES_NO_OPTION);
			
			if(response == JOptionPane.YES_OPTION){
				this.engine.signOff();
				this.dispose();
				System.exit(0);
			}
			
		}
		
		private void viewHistoryOptionActionPerformed(ActionEvent evt) {
			
			engine.showHistory();
			
		}
}
